import {Component, OnInit, AfterViewInit, ElementRef, Renderer2, ViewChild, OnDestroy} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import {ApesMessageService} from "@shared/apes/message";
import {CompanyModalComponent} from "../company-modal/company-modal.component";
import {AnalysisService} from "../analysis.service";
import {UserAuthService} from "@core/services/user-auth.service";
import {Router} from "@angular/router";

@Component({
  selector: 'custom-service-control',
  templateUrl: './custom-service-control.component.html',
  styleUrls: ['./custom-service-control.component.scss']
})
export class CustomServiceControlComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild(CompanyModalComponent, {static: false}) child: CompanyModalComponent;
  private timer;
  private timers;
  private timeres;

  // 时间相关
  todayTimes: Date;
  dateTimes: any[] = [];
  months: Date;
  dateMonths: any[] = [];

  // 分页相关
  tablesIndex: number = 0;
  currentTablesList: any[];

  // 右侧进度条相关
  format = percent => `${percent}%`;

  // 脑袋汇总
  headList: any[];
  titleData = {};
  oneList = {};
  twoList = {};

  // 评论区相关
  pageData: any[];

  companyLocal = this.as.getLocalObj();
  companyData = [];
  company: any;
  userInfo = this.userAuthService.getUserInfoObj();
  keyNum: any = 0;
  clickTime: any;
  bottomStep: any[];
  pageIndex = 0;
  year: any;
  companyLogo: any;                               // 5e746d2839bf6200014e3b20
  logoTitle: any;
  host:any = window.location.host;                // test57-6060.jekunauto.cn
  // host:any = 'test57-6060.jekunauto.cn';                // test57-6060.jekunauto.cn

  constructor(private apiService: ApiService,
              private el: ElementRef,
              private renderer: Renderer2,
              private msg: ApesMessageService,
              private as: AnalysisService,
              private userAuthService: UserAuthService,
              private router: Router,) {
    if (this.companyLocal) {
      let company: any = this.companyLocal;
      let data = [];
      for (let item of company) {
        for (let list of item['array']) {
          data.push(list.id);
        }
      }
      this.company = this.as.unique(data);
    } else if (this.userInfo) {
    } else {
      this.router.navigateByUrl('/analysis/control/index');
    }

    const time = (1000 * 60) * 10;
    this.timer = setInterval(() => {                        // 脑袋 评论区 进度条 每10钟请求一次
      this.getHeadTop();
      this.getMeterData();
      this.getHead();
      this.headList = this.setHeadData();
      this.getCommentData();
      this.getRework();
    }, time)

    this.timers = setInterval(() => {                        //  每10秒 轮播评论数据
      this.currentTablesList = [];
      this.currentTablesList = this.pageList(this.pageData, 3);
      this.bottomStep = [];
      this.bottomStep = this.page(this.bottomLeft.data, 2);
      this.getVisit();
    }, 10000)

    this.timeres = setInterval(() => {                        //  每秒刷新时间
      this.dateTimes = [];
      this.dateMonths = [];
      this.getMonths();
      this.getTodayTimes();
    }, 1000)
  };

  ngOnInit() {
    const date = new Date();
    this.year = date.getFullYear();
    this.as.getImges('如约车服1').then(value => {
      this.logoTitle = value;
      this.companyLogo = value ? 'https://'+this.host+'/fileserver/view/'+value : './assets/tmp/img/bi/swzx_02.png';
    });
    this.companyData = this.company;
    this.changeCompany(this.companyData);
  }

  changeCompany(e) {
    this.companyData = e;
    this.getHeadTop();
    this.headList = this.setHeadData();
    this.getCommentData();
    this.getRework();
    this.getVisit();
    this.getMeterData();
    this.getHead();
    this.initFocus();
  }

  ngAfterViewInit() {
    const content = document.querySelector('#Boxs');
    const _body = document.querySelector('body');
    if (_body.clientWidth > 1920) {
      let _zoom = _body.clientWidth / content.clientWidth;
      setTimeout(() => {
        this.renderer.setStyle(content, 'zoom', _zoom);
      }, 100);
    }
  }

  // 返回上一页
  goBack($event: any) {
    let key = $event.button;
    if (key === 2) {
      history.go(-1);
      return false;
    }
  }

  getMonths() {
    this.months = new Date();
    this.dateMonths = [];
    let shijian = 0;
    let riqi = 1;
    let newTimes;
    let month = this.months.toTimeString();
    for (let i = 0, len = month.length; i < len; i++) {
      newTimes = month.slice(shijian, riqi);
      this.dateMonths.push(newTimes);
      shijian++;
      riqi++;
    }
    this.dateMonths = this.dateMonths.filter((value) => value !== ":");
  };

  getTodayTimes() {
    this.todayTimes = new Date();
    this.dateTimes = [];
    let shijian = 0;
    let riqi = 1;
    let newTimes;
    let todayTime = this.todayTimes.toISOString();
    for (let i = 0, len = todayTime.length; i < len; i++) {
      newTimes = todayTime.slice(shijian, riqi);
      this.dateTimes.push(newTimes);
      shijian++;
      riqi++;
    }
    this.dateTimes = this.dateTimes.filter((value) => value !== "-");
  };

  // 头部第一段
  getHeadTop() {
    let data = {'pdata': {'companyId': this.companyData}};
    this.apiService.post('crm.customComplain.queryComplainNum', {'body': JSON.stringify(data)}).subscribe(
      (body) => {
        if (body) {
          this.oneList = body;
          // this.rateNum = body.CREATE_NUM;

        } else {
          this.msg.info(body.msg);
        }
      });
  };

  setHeadData() {
    return [
      {
        titleData: [
          {lable: '今日新增', feild: 'CREATE_NUM', style: true},
          {lable: '待分配', feild: 'WAIT_OA_NUM', style: true},
          {lable: '待处理', feild: 'WAIT_DEAL_NUM', style: true},
          {lable: '停单中', feild: 'STOP_NUM', style: true},
          {lable: '待结单', feild: 'END_NUM', style: true},
          {lable: '昨日差评率', feild: 'badCommentRate', style: false},
          {lable: '昨日客诉率', feild: 'complainRate_yes', style: false},
          {lable: '月客诉总量', feild: 'monthNum', style: true},
          {lable: '月客诉率', feild: 'complainRate_mon', style: false},
          {lable: '月返修', feild: 'YFX', style: true},
          {lable: '返修率', feild: 'FXL', style: false},
        ]
      }
    ]
  };

  rightList = [
    {
      api: 'ipmKFZKForAppService.getCSBC',
      title: '超时补偿',
      color: '#FB0018',
      pages: 4,
      tabWidth: '98%',
      titleList: [
        {lable: '门店', feild: 'MDMC', width: '12%'},
        {lable: '单数', feild: 'DS', width: '5%'},
        {lable: '金额(元)', feild: 'JE', width: '8%'},
        {lable: '月累计金额', feild: 'YJE', width: '10%'},
      ]
    },
    {
      api: 'ipmKFZKForAppService.getZBBC',
      title: '合约质保、返工赔偿',
      color: '#FB0018',
      pages: 4,
      tabWidth: '98%',
      titleList: [
        {lable: '门店', feild: 'MDMC', width: '12%'},
        {lable: '单数', feild: 'DS', width: '5%'},
        {lable: '金额(元)', feild: 'JE', width: '8%'},
        {lable: '月累计金额', feild: 'YJE', width: '10%'},
      ]
    },
    {
      api: 'ipmKFZKForAppService.getSaveBeyondTime',
      title: '救援超时',
      color: '#FB0018',
      pages: 4,
      tabWidth: '98%',
      titleList: [
        {lable: '车牌号', feild: 'CPHM', width: '14%', logo: 'TPLJ'},
        {lable: '指派门店', feild: 'MDMC', width: '14%'},
        {lable: '耗时', feild: 'time', width: '10%'}
      ]
    }
  ];

  bottomLeft = {
    XZZT: 0,
    DJDZT: 0,
    DFTZT: 0,
    DFGBC: 0,
    data: [
      {
        MDMC: '广州渔人码头店',
        CPHM: '粤A888888',
        TPLJ: '',
        ZHS: 1500,
        ZT: '已确认',
        item: [
          {Description: "50分钟", title: '外返', type: "审核", status: "stringMore"},
          {Description: '2小时', type: '鉴定', title: "个人、公司", status: "stringMore"},
          {Description: '50分钟', type: "责任分摊", title: "伍莉莉", status: "string"},
          {title: "", type: "返工补偿", status: "stringMore"}
        ]
      },
      {
        MDMC: '广州渔人码头店',
        CPHM: '粤A888888',
        TPLJ: '',
        ZHS: 1500,
        ZT: '已确认',
        item: [
          {Description: "50分钟", title: '外返', type: "审核", status: "stringMore"},
          {Description: '2小时', type: '鉴定', title: "个人、公司", status: "stringMore"},
          {Description: '50分钟', type: "责任分摊", title: "伍莉莉", status: "string"},
          {title: "", type: "返工补偿", status: "stringMore"}
        ]
      },
    ],
  };

  visitData = [
    // { headerName: '应回访', field: 'YHFL' },
    // { headerName: '待回访', field: 'DHFL' },
    // { headerName: '实际回访', field: 'SJHFL' },
    // { headerName: '回访成功', field: 'HFCGL' },
    // { headerName: '继续跟踪', field: 'JXGZL' },
    // { headerName: '终止回访', field: 'ZZHFL' },
    // { headerName: '成功率', field: 'CGL' }
    { headerName: '上日剩余', field: 'REST_NUM' },
    { headerName: '今日新增', field: 'ADD_NUM' },
    { headerName: '应回访', field: 'SHOULD_NUM' },
    { headerName: '待回访', field: 'WAIT_NUM' },
    { headerName: '回访成功', field: 'SUCCESS_NUM' },
    { headerName: '继续回访', field: 'AGAIN_NUM' },
    { headerName: '终止回访', field: 'STOP_NUM' },
    { headerName: '成功率', field: 'SUCCESS_RATE' },
    { headerName: '拨号量', field: 'CALL_NUM' }
  ];

  satisfied = [
    { headerName: '非常满意', field: 'FCMY' },
    { headerName: '满意', field: 'MY' },
    { headerName: '一般', field: 'YB' },
    { headerName: '不满意', field: 'BMY' },
    { headerName: '非常不满意', field: 'FCBMY' },
    { headerName: '不满意率', field: 'BMYL' }
  ];

  bottomCenter = {
    dailyQuantity:{"ADD_NUM":0,"SHOULD_NUM":0,"SUCCESS_NUM":0,"WAIT_NUM":0,"AGAIN_NUM":0,"STOP_NUM":0,"REST_NUM":0,"CALL_NUM":0,"SUCCESS_RATE":"0.0%"},
    monthQuantity:{"ADD_NUM":0,"SHOULD_NUM":0,"SUCCESS_NUM":0,"WAIT_NUM":0,"AGAIN_NUM":0,"STOP_NUM":0,"REST_NUM":0,"CALL_NUM":0,"SUCCESS_RATE":"0.0%"},
    monthlySatisfaction:{"BMYL":"0.0%","MYL":"0.0%","FCBMY":0,"YB":0,"FCMY":0,"MY":0,"BMY":0}
  };

  // 下 三表
  // reportList = [
  //   {
  //     api: 'ipmKFZKForAppService.getSaveBeyondTime',
  //     title: '救援超时',
  //     pages: 5,
  //     tabWidth: '387px',
  //     titleList: [
  //       // {lable: '手机号', feild: 'mobile', width: '120px'},
  //       {lable: '车牌号', feild: 'CPHM', width: '130px', logo: 'TPLJ'},
  //       {lable: '指派门店', feild: 'MDMC', width: '140px'},
  //       // {lable: '指派人', feild: 'RYMC', width: '85px'},
  //       {lable: '耗时', feild: 'time', width: '120px'}
  //     ]
  //   }
  // ];

  // 上 左
  getCommentData() {
    let data = {'pdata': {'companyId': this.companyData}};
    this.apiService.post('crm.customComplain.complainControlsNode', {'body': JSON.stringify(data)}).subscribe(
      (body) => {
        if (body) {
          this.pageData = body;
          this.currentTablesList = this.pageList(this.pageData, 3);
          if (this.pageData.length === 0) {
            this.msg.info(`未找到满足条件的数据`);
          }
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  // 头部第二段
  getMeterData() {
    let data = {'interfaceMethod': 'ipmKFZKForAppService.getPJ', 'pdata': {'companyId': this.companyData}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.twoList = data;
            this.titleData = Object.assign(this.oneList,data);
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 头部第三段
  getHead() {
    let data = {'interfaceMethod': 'ipmKFZKForAppService.getKFHead', 'pdata': {'companyId': this.companyData}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.titleData = Object.assign(this.oneList, this.twoList, data);
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  //  回访
  getVisit() {
    let data = {'interfaceMethod': 'shhfdService.queryProjectControl', 'pdata': {'companyId': this.companyData}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          let data = JSON.parse(result.obj);
          this.bottomCenter = data;
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  //  返修鉴定
  getRework() {
    let data = {'interfaceMethod': 'ipmKFZKForAppService.getFXJD', 'pdata': {'companyId': this.companyData}};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          let data = JSON.parse(result.obj);
          this.bottomLeft = data;
          this.bottomStep = this.page(this.bottomLeft.data, 2);
        } else {
          this.msg.info(result.msg);
        }
      });
  }

// 评论区 分页
  pageList(arrData: any[], page: number) {
    const count = arrData.length;
    const data = [];
    let tempIndex = 0;
    for (let i = this.pageIndex; i < count; i++) {
      if (tempIndex < page) {
        data.push(arrData[i]);
      } else {
        break;
      }
      tempIndex++;
      this.pageIndex++;
    }
    //当数据遍历完 重新请求数据
    if (this.pageIndex >= count) {
      this.pageIndex = 0;
    }
    return data;
  };

  page(arrData: any[], page: number) {
    const count = arrData.length;
    const data = [];
    let tempIndex = 0;
    for (let i = this.tablesIndex; i < count; i++) {
      if (tempIndex < page) {
        data.push(arrData[i]);
      } else {
        break;
      }
      tempIndex++;
      this.tablesIndex++;
    }
    //当数据遍历完 重新请求数据
    if (this.tablesIndex >= count) {
      this.tablesIndex = 0;
    }
    return data;
  };

// 显示 天 时 分 换算
  toHourMinute(minutes) {
    minutes = Number(minutes);
    if (typeof(minutes) == 'number') {
      if (Math.floor(minutes / 60 / 24) >= 1) {
        if (Math.floor(minutes / 60 / 24) < 10) {
          return (Math.floor(minutes / 60 / 24) + '天' + (minutes % 60 % 24) + '小时');
        }
        return (Math.floor(minutes / 60 / 24) + '天');
      } else if (Math.floor(minutes / 60 / 24) < 1) {
        if (Math.floor(minutes) < 60) {
          return (Math.floor(minutes % 60) + '分钟');
        }
        return (Math.floor(minutes / 60) + '小时' + (minutes % 60) + '分钟');
      }
    } else {
      return minutes;
    }

  }

  private $(id) {
    return document.getElementById(id);
  }

// 获取焦点
  initFocus() {
    this.$('system').focus();
  }

  getFocus() {
  }

  getKey($event, click?: any) {
    $event.preventDefault();
    let key = $event.keyCode;
    if (click === 1) {
      key = 0;
    }
    if (key === 0) {
      if (this.keyNum > 0) {
        this.onDblClick();
      } else {
        this.onClick();
      }
    }
    this.initFocus();
  }

  onClick() {
    clearTimeout(this.clickTime);
    this.keyNum++;
    this.clickTime = setTimeout(() => {
      this.keyNum = 0;
      this.router.navigateByUrl('/analysis/control/index');
    }, 500);
  }

  onDblClick() {
    clearTimeout(this.clickTime);
    this.child.isVisible = true;
    this.keyNum = 0;
  }

  ngOnDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    if (this.timers) {
      clearInterval(this.timers);
    }
    if (this.timeres) {
      clearInterval(this.timeres);
    }
  }
}
